<?php

namespace App\Services\Admin\Sponsor;

use App\Exceptions\SponsorException;
use Exception;

class CategoryService extends BaseSponsorService
{

    /**
     * 分类列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {
        // 查询分类总条数
        $total = $this->getSponsorCategoryModel()->total($params);

        // 查询分类列表
        $categoryList = $this->getSponsorCategoryModel()->list($params, [
            'id', 'title', 'img_url'
        ]);

        $list = [];
        foreach ($categoryList as $item) {
            $list[] = [
                'id' => $item['id'],
                'title' => $item['title'],
                'imgUrl' => $item['img_url']
            ];
        }

        return [
            'total' => $total,
            'list' => $list,
        ];
    }

    /**
     * 创建分类
     * @return void
     * @throws Exception
     */
    public function create(array $params)
    {
        // 查询分类是否存在
        $category = $this->getSponsorCategoryModel()->getItemByTitle($params['title']);
        if ($category) {
            throw new SponsorException('分类已存在', SponsorException::CODE_2001);
        }

        $createData = [
            'title' => $params['title'],
            'img_url' => $params['imgUrl']
        ];

        $this->getSponsorCategoryModel()->addItem($createData);
    }

    /**
     * 更新分类
     * @param array $params
     * @return void
     * @throws SponsorException
     * @throws Exception
     */
    public function update(array $params)
    {
        // 查询分类是否存在
        $category = $this->getSponsorCategoryModel()->getItemById($params['id']);
        if (empty($category)) {
            throw new SponsorException('分类不存在', SponsorException::CODE_2002);
        }

        $updateData = [];
        if (!empty($params['title'])) {
            $updateData['title'] = $params['title'];
        }
        if (!empty($params['imgUrl'])) {
            $updateData['img_url'] = $params['imgUrl'];
        }

        $updateData && $this->getSponsorCategoryModel()->updateItemById($params['id'], $updateData);
    }

    /**
     * 删除分类
     * @return void
     * @throws Exception
     */
    public function delete(array $params)
    {
        // 查询分类是否存在
        $category = $this->getSponsorCategoryModel()->getItemById($params['id']);
        if (empty($category)) {
            throw new SponsorException('分类不存在', SponsorException::CODE_2002);
        }

        // 查询分类是否在使用
        $sponsorGoods = $this->getSponsorGoodsModel()->getItemByCategoryId($params['id']);
        if ($sponsorGoods) {
            throw new SponsorException('分类已被使用，不能删除', SponsorException::CODE_2003);
        }

        // 删除分类
        $this->getSponsorCategoryModel()->deleteItemById($params['id']);
    }
}
